package sicau.carManager.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.client.RestTemplate;
import sicau.carManager.Util.TokenUtil.MD5Util;
import sicau.carManager.entity.Admin;
import sicau.carManager.entity.BlackList;
import sicau.carManager.result.R;
import sicau.carManager.service.BlackListService;
import sicau.carManager.service.FixedCarInformationService;
import springfox.documentation.spring.web.json.Json;

import javax.xml.ws.Response;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <p>
 *  前端控制器
 * </p>
 * 代码简单，就没有写service层
 * @author ITcz
 * @since 2021-02-05
 */
@Slf4j
@RestController
@RequestMapping("/black-list")
@CrossOrigin
public class BlackListController {

    @Autowired
    BlackListService blackService;

    @Autowired
    FixedCarInformationService fixService;

    @Autowired
    private RestTemplate restTemplate;

    /*使用restTemplate调用蓝卡api需要准守的规定：
    * 所有请求/返回数据格式采用UTF-8格式;
所有请求采用HTTP 协议，POST请求方式;
所有请求数据依据标准格式加密:md5(key+parkNumber) ,key由蓝卡开发者分配,每次请求时需要在请求头中加入一个字段sign,sign字段的值即md5加密后的密文,返回数据无需加密,注意:加密后的密文采用32位小写格式;
请求返回采用同步方式;
所有数据采用JSON形式;
金额以String表示，单位 元;
所有时间格式采用yyyy-MM-dd HH:mm:ss格式，24小时制形式,如有特殊格式要求则依据字段说明而定;
*****所有请求示例仅供参考,不可直接进行测试
本文所有接口中的parkNumber字段由蓝卡分配
    * */
    //注:所有请求需要在请求头中加入签名sign,sign生成规则: String sign = md5(key+parkNumber),key由蓝卡分配
    //雅安校区的parkNumber
    private final String yaAnParkNumber = "p200713143536";
    private final String yaAnSign = "2a1ac789a5a1bc8b1ab67d7029dc6d72";

    //温江校区的parkNumber
    private final String wenJiangParkNumber = "p200713145437";
    private final String wenJiangSign = "426d2985aa0dd727dde7e3e0f09babf8";

    //都江堰校区的parkNumber
    private final String duJiangYanParkNumber = "";
    private final String duJiangYanSign = "";


    @PostMapping("/add/car")
    @ApiOperation("将车辆列入蓝卡黑名单")
    public R addCar(Admin admin, @ApiParam("列入黑名单的车牌") @RequestParam("licensePlate") String licensePlate){
        //创建请求的HashMap
        HashMap requestMap = new HashMap();
        //创建请求的请求头,并添加sign签名
        HttpHeaders requestHeaders = new HttpHeaders();
        //根据校区设置    parkNumber	字符串	必填	场库编号	每个场库的唯一编号
        String campus = admin.getCampus();
        //这种写法是错的：campus == "雅安"!,必须用equals()方法!
        if ("雅安".equals(campus)) {
            requestHeaders.add("sign", yaAnSign);
            requestMap.put("parkNumber", yaAnParkNumber);
        }else if ("温江".equals(campus)) {
            requestHeaders.add("sign", wenJiangSign);
            requestMap.put("parkNumber", wenJiangParkNumber);
        }else if ("都江堰".equals(campus)) {
            requestHeaders.add("sign", duJiangYanSign);
            requestMap.put("parkNumber", duJiangYanParkNumber);
        }
        //source	字符串	必填	来源	线上/线下
        requestMap.put("source", "线上");
        //size	Int	必填	本次黑名单数量
        requestMap.put("size", 1);
        //datas	JSON数组	必填	黑名单列表	注:此字段格式并非字符串
        //datas取值:
            //plate	字符串	必填	车牌号	车牌号
            //memo	字符串	必填	备注	无内容时为""
        HashMap data = new HashMap();
        List<Map<String, String>> datas = new ArrayList<Map<String, String>>();
        data.put("memo", "");
        data.put("plate", licensePlate);
        datas.add(data);
        requestMap.put("datas", datas);
        //将请求体和请求头放入请求中,请求参数全部为JSON格式
        System.out.println(JSON.toJSONString(requestMap));
        HttpEntity requestEntity =new HttpEntity(JSON.toJSONString(requestMap), requestHeaders);
        //向蓝卡发送请求
        final ResponseEntity<String> responseEntity = restTemplate.exchange("http://47.92.199.193:8080/bcopenapi/out/synBlack", HttpMethod.POST,  requestEntity, String.class);
        //获得请求的返回结果
        final String body = responseEntity.getBody();
        String content = body;
        String pattern = ".*\"status\".*\"fail\".*";
        //判断body中是否有字符串"status"*"fail"
        boolean isMatch = Pattern.matches(pattern, content);
        //如果有，那么请求失败了
        if (isMatch) {
            return R.error(500602, "蓝卡黑名单添加失败！");
        }
        //请求成功了,将车辆信息添加到数据库中
        BlackList blackList = new BlackList();
        blackList.setLicensePlateNumber(licensePlate);
        blackList.setCampus(admin.getCampus());
        //查询联系电话
        String phoneNumber = fixService.getPhoneNumberByLicensePlate(licensePlate);
        if (phoneNumber != null) {
            blackList.setPhoneNumber(phoneNumber);
        }
        //保存至数据库
        blackService.save(blackList);
        return R.ok("添加成功");
    }


    @PostMapping("/delete/car")
    @ApiOperation("将车辆从蓝卡黑名单中移除")
    public R deleteCar(Admin admin, @ApiParam("列入黑名单的车牌") @RequestParam("licensePlate") String licensePlate){
        //创建请求的HashMap
        HashMap requestMap = new HashMap();
        //创建请求的请求头,并添加sign签名
        HttpHeaders requestHeaders = new HttpHeaders();
        //根据校区设置    parkNumber	字符串	必填	场库编号	每个场库的唯一编号
        String campus = admin.getCampus();
        if ("雅安".equals(campus)) {
            requestHeaders.add("sign", yaAnSign);
            requestMap.put("parkNumber", yaAnParkNumber);
        }else if ("温江".equals(campus)) {
            requestHeaders.add("sign", wenJiangSign);
            requestMap.put("parkNumber", wenJiangParkNumber);
        }else if ("都江堰".equals(campus)) {
            requestHeaders.add("sign", duJiangYanSign);
            requestMap.put("parkNumber", duJiangYanParkNumber);
        }
        //plate	字符串	必填	车牌号	车牌号
        requestMap.put("plate", licensePlate);
        //将请求体和请求头放入请求中,请求参数全部为JSON格式
        System.out.println(JSON.toJSONString(requestMap));
        HttpEntity requestEntity = new HttpEntity(JSON.toJSONString(requestMap), requestHeaders);
        //向蓝卡发送请求
        final ResponseEntity<String> responseEntity = restTemplate.exchange("http://47.92.199.193:8080/bcopenapi/out/delBlack", HttpMethod.POST, requestEntity, String.class);
        //获得请求的返回结果
        final String body = responseEntity.getBody();
        String content = body;
        String pattern = ".*\"status\".*\"fail\".*";
        //判断body中是否有字符串"status"*"fail"
        boolean isMatch = Pattern.matches(pattern, content);
        //如果有，那么请求失败了
        if (isMatch) {
            return R.error(500602, "蓝卡黑名单移除失败！");
        }
        //请求成功了,将车辆信息从数据库中删除
        int i = blackService.removeByLicensePlate(licensePlate, admin.getCampus());
        if (i == 0) {
            return R.error(500603, "本地黑名单无此车辆信息！");
        }
        return R.ok("移除黑名单成功");
    }


    @GetMapping("/getList")
    @ApiOperation("显示所有黑名单车辆")
    public R deleteCar(Admin admin) {

        HashMap map = new HashMap();

        map.put("list", blackService.getList(admin.getCampus()));

        return R.ok(map);
    }


}

